﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tools.Base
{
    public class MyConsole
    {
        public static void WriteLine(string value)
        {
            lock (_mutex)
            {
                Console.WriteLine(value);
                
                if (_bToLog)
                {
                    LogManager.WriteLog(value, null);
                }
            }
        }

        public static void WriteLineEx(string value, ConsoleColor foreground_color = ConsoleColor.White, ConsoleColor background_color = ConsoleColor.Black)
        {
            string[] values = new string[] { value };
            WriteLineEx(values, foreground_color, background_color);
        }

        public static void WriteLineEx(string[] value, ConsoleColor foreground_color = ConsoleColor.White, ConsoleColor background_color = ConsoleColor.Black)
        {
            lock (_mutex)
            {
                ConsoleColor oldForegroundColor = Console.ForegroundColor;
                ConsoleColor oldBackgroundColor = Console.BackgroundColor;

                Console.ForegroundColor = foreground_color;
                Console.BackgroundColor = background_color;

                for(int i = 0; i < value.Length; i++)
                {
                    if(i == value.Length - 1)
                    {
                        Console.WriteLine(value[i]);
                    }
                    else
                    {
                        Console.Write(value[i]);
                        int nLn = Console.CursorTop;
                        Console.SetCursorPosition(20, nLn);
                    }
                }

                Console.ForegroundColor = oldForegroundColor;
                Console.BackgroundColor = oldBackgroundColor;

                if (_bToLog)
                {
                    StringBuilder sb = new StringBuilder();
                    for(int i = 0; i < value.Length; i++)
                    {
                        if(sb.Length != 0)
                        {
                            sb.Append(' ');
                        }

                        sb.Append(value[i]);
                    }

                    LogManager.WriteLog(sb.ToString(), null);
                }
            }
        }

        /// <summary>
        /// 锁
        /// </summary>
        private static object _mutex = new object();

        /// <summary>
        /// 是否写LOG
        /// </summary>
        private static bool _bToLog = true;
    }
}
